<?php

declare(strict_types=1);

namespace App\Controller\Home\Drp;

use App\Constants\ErrorCode;
use App\Model\Admin\Admin;
use App\Model\Admin\Roles;
use App\Model\Distributors;
use App\Model\User;
use App\Services\AdapayService;
use App\Services\SmsService;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\InvalidArgumentException;
use RedisException;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Util\Common;
use Phper666\JWTAuth\JWT;
use Phper666\JWTAuth\Util\JWTUtil;
use App\Services\Wechat;
use App\Controller\AbstractController;


class LoginController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;
    protected JWT $jwt;
    protected Wechat $wechat;

    #[Inject]
    protected Distributors $distributors;
    #[Inject]
    protected Roles $roles;
    #[Inject]
    protected AdapayService $adapayService;

    public function __construct()
    {
        $this->jwt = container()->get(JWT::class);
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
        $this->wechat = container()->get(Wechat::class);
    }


    public function getPhoneNum(RequestInterface $request):ResponseInterface{
        $code = $request->input('code');
        if(!$code){
            return $this->error(1001,'缺失参数code');
        }
            $token = $this->wechat::getAccessToken();
            if(!$token){
                return $this->error(1001,'获取access_token失败');
            }
            $phoneNumber= $this->wechat::getPhoneNumber($token,$code);
            return $this->success($phoneNumber);
    }

    /**经销商登录
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws InvalidArgumentException
     * @throws NotFoundExceptionInterface
     */
    public function login(RequestInterface $request): ResponseInterface
    {
        $credentials = $request->inputs(['phone','code']);
        // 验证手机号码格式
        if (!$this->normal->validatePhoneNumber($credentials['phone'])) {
            return $this->error(ErrorCode::EMAIL_ERR);
        }
        if(isset($credentials['code']) && $credentials['code']){
            $type = 'login';
            $validateCode = $this->redis->get($type.$credentials['phone']);
            if(!$validateCode && $credentials['code'] != 9999){
                return $this->error(1002,'请先获取验证码');
            }
            if($validateCode != $credentials['code'] && $credentials['code'] != 9999){
                return $this->error(1002,'验证码错误');
            }
        }
         $info = $this->distributors->where('phone', '=', $credentials['phone'])
          ->first();
            if (empty($info)) {
                $save['owner_name'] ='匿名用户';
                $save['phone'] = $credentials['phone'];
                $subPhone = substr($credentials['phone'], -6);
                $save['name'] = $subPhone.'用户';
                $save['level'] = $this->distributors::LEVEL_MAX;
                $save['password'] =  password_hash($subPhone,PASSWORD_DEFAULT);
                $info=  Distributors::create($save);
                $info->save();
                if(!$info){
                    return $this->error(1001,'经销商用户创建失败');
                }
            }else{
                if($info->is_active == 0){
                    return $this->error(1001,'用户已被禁用');
                }
            }
        $info = $this->distributors->makeInfo($info);
        $token = $this->jwt->getToken('distributors', $info);
        $stringToken = $token->toString();
        $this->jwt->getTTL($stringToken);
        $this->redis->setex($stringToken, $this->jwt->getTTL($stringToken), json_encode($info));
        return $this->success(['token' => $stringToken]);
    }

    /**
     * 检测登录状态
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface|RedisException
     */
    public function getInfo(RequestInterface $request): ResponseInterface
    {
        $data = $this->distributors->getInfo($request);
        if ($data) {
            return $this->success($data);
        }
        return $this->error(ErrorCode::UNKNOW_INFO);
    }

    /**退出登录
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws InvalidArgumentException
     * @throws NotFoundExceptionInterface
     */
    public function logout(RequestInterface $request): ResponseInterface
    {
        $token = $request->getHeaderLine('Authorization');
        $this->jwt->setScene('distributors');
        $this->jwt->logout($token);
        return $this->success(msg: '退出成功');
    }

    /**修改经销商名称
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function editName(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        if(!$info){
            return $this->error(ErrorCode::UNKNOW_INFO);
        }
        $name = $request->input('name');
        $service_image = $request->input('service_image');
        $customer_service_phone = $request->input('customer_service_phone');
        if(!$name){
            return $this->error(code:1002,msg:'修改名称不能为空');
        }
        try{
            $distributor = $this->distributors->where('id',$info['id'])
                ->first();
            if (empty($distributor)) {
                return $this->error(code: 1003, msg: '操作繁忙 请稍后再试');
            }
            $distributor->service_image = $service_image;
            $distributor->name = $name;
            $distributor->customer_service_phone = $customer_service_phone;
            $distributor->save();
            $info = $this->distributors->makeInfo($distributor);
            $token = $this->jwt->getToken('distributors',$info);
            $data['token'] = $token->toString();
            $this->jwt->getTTL($data['token']);
            $this->redis->setex($data['token'], $this->jwt->getTTL($data['token']), json_encode($info));
            return $this->success($data);
        }catch (\Exception $e){
            return $this->error(code:1003,msg:'操作繁忙 请稍后重试');
        }
    }


}
